package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.catering.common.seller.context.SellerContextHolder;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.food.api.RemoteFoodService;
import com.ruoyi.food.api.model.FoodDiscountVo;
import com.ruoyi.system.domain.ActivityDiscount;
import com.ruoyi.system.domain.ActivityDiscountDetail;
import com.ruoyi.system.mapper.ActivityDiscountMapper;
import com.ruoyi.system.service.ActivityDiscountDetailService;
import com.ruoyi.system.service.ActivityDiscountService;
import com.ruoyi.system.utils.ReplaceUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 活动折扣服务impl
 *
 * @author Administrator
 * @date 2023/03/13
 */
@Service
public class ActivityDiscountServiceImpl extends ServiceImpl<ActivityDiscountMapper, ActivityDiscount> implements ActivityDiscountService {

    @DubboReference
    private RemoteFoodService remoteFoodService;

    @Resource
    private ActivityDiscountDetailService activityDiscountDetailService;

    @Override
    public TableDataInfo<ActivityDiscount> pageActivityDiscount(ActivityDiscount activityDiscount, PageQuery pageQuery) {
        Integer status = activityDiscount.getStatus();
        String discountName = activityDiscount.getDiscountName();
        SellerContextHolder.getSellerId();
        return TableDataInfo.build(baseMapper.selectPage(pageQuery.build(), Wrappers.lambdaQuery(ActivityDiscount.class).eq(StrUtil.isNotBlank(discountName), ActivityDiscount::getDiscountName, discountName).eq(ObjUtil.isNotNull(status), ActivityDiscount::getStatus, status)));
    }

    @Override
    public int saveActivityDiscount(ActivityDiscount activityDiscount) {
        if (activityDiscount.getRoleList() != null) {
            activityDiscount.setAuthRoleList(ReplaceUtil.replaceZKH(activityDiscount.getRoleList().toString()));
        }
        if (activityDiscount.getRoleList() != null) {
            activityDiscount.setTimeIntervalId(ReplaceUtil.replaceZKH(activityDiscount.getTimeIntervalList().toString()));
        }
        return baseMapper.insert(activityDiscount);
    }

    @Override
    public int updateActivityDiscount(ActivityDiscount activityDiscount) {
        if (activityDiscount.getRoleList() != null) {
            activityDiscount.setAuthRoleList(ReplaceUtil.replaceZKH(activityDiscount.getRoleList().toString()));
        }
        if (activityDiscount.getRoleList() != null) {
            activityDiscount.setTimeIntervalId(ReplaceUtil.replaceZKH(activityDiscount.getTimeIntervalList().toString()));
        }
        return baseMapper.updateById(activityDiscount);
    }

    @Override
    public ActivityDiscount getActivityDiscountById(Long discountId) {
        ActivityDiscount activityDiscount = baseMapper.selectById(discountId);
        if (ObjUtil.isNull(activityDiscount)) {
            throw new ServiceException("数据不存在，请刷新重试或联系管理员");
        }
        activityDiscount.setRoleList(getList(activityDiscount.getAuthRoleList()));
        activityDiscount.setTimeIntervalList(getList(activityDiscount.getTimeIntervalId()));
        return activityDiscount;
    }

    @Override
    public TableDataInfo<FoodDiscountVo> pageFoodDetail(ActivityDiscount activityDiscount, PageQuery pageQuery) {
        // 获取折扣详情
        IPage<FoodDiscountVo> page = baseMapper.pageFoodDetail(pageQuery.build(), new QueryWrapper<>()
            .eq(ObjUtil.isNotNull(activityDiscount.getDiscountId()), "tad.discount_id", activityDiscount.getDiscountId()));
        List<FoodDiscountVo> records = page.getRecords();
        // 通过折扣详情获取菜品详情
        if (CollUtil.isNotEmpty(records)) {
            List<Long> foodIds = records.stream().map(FoodDiscountVo::getFoodId).collect(Collectors.toList());
            Map<Long, FoodDiscountVo> voMap = remoteFoodService.listFoodDetailByFoodIds(foodIds);
            records.forEach(item -> {
                FoodDiscountVo foodDiscountVo = voMap.get(item.getFoodId());
                if (ObjUtil.isNotNull(foodDiscountVo)) {
                    item.setClassificationName(foodDiscountVo.getClassificationName());
                    item.setFoodName(foodDiscountVo.getFoodName());
                }
            });
            page.setRecords(records);
        }
        return TableDataInfo.build(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> discountIds) {
        baseMapper.deleteBatchIds(discountIds);
         activityDiscountDetailService.remove(Wrappers.lambdaQuery(ActivityDiscountDetail.class)
            .in(ActivityDiscountDetail::getDiscountId, discountIds));
    }


    /**
     * 得到列表
     *
     * @param str str
     * @return {@link List}<{@link Long}>
     */
    private List<Long> getList(String str) {
        List<Long> list = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(str)) {
            if (StrUtil.contains(str, ",")) {
                CollUtil.addAll(list, StrUtil.split(str, ',').stream().mapToLong(Long::parseLong).boxed().collect(Collectors.toList()));
            } else {
                list.add(NumberUtil.parseLong(str));
            }
        }
        return list;
    }
}
